package com.library;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/add_book")
public class AddBookServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET,POST");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type");
        response.setContentType("application/json; charset=UTF-8");

        String number = request.getParameter("number");
        String name   = request.getParameter("name");
        String author = request.getParameter("author");

        PrintWriter out = response.getWriter();
        if (number == null || name == null || author == null 
                || number.isEmpty() || name.isEmpty() || author.isEmpty()) {
            out.print("{\"success\": false, \"message\": \"Missing parameter\"}");
            return;
        }

        Book newBook = new Book(number, name, author);
        boolean result = BookDAO.addBook(newBook);
        if (result) {
            out.print("{\"success\": true, \"message\": \"Book added successfully\"}");
        } else {
            out.print("{\"success\": false, \"message\": \"Failed to add book (maybe duplicate number)\"}");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        doGet(request, response);
    }
}

